package com.yuantu.judiciary.model.word;


import com.yuantu.judiciary.utils.PdfUtil;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.contentstream.PDFStreamEngine;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.rendering.PageDrawer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author kgwei
 */
public class WordMaker {

    public static XWPFDocument makeWord(List<WordElement> wordElements) {
        XWPFDocument document = new XWPFDocument();
        wordElements.forEach(wordElement -> wordElement.addElement(document));
        return document;
    }

    public static void downLoadWordWithData(String fileName, HttpServletResponse response, List<WordElement> wordElements) {
        XWPFDocument document = new XWPFDocument();
        wordElements.forEach(wordElement -> wordElement.addElement(document));
        downLoadWord(fileName, response, document);
    }

    public static void downLoadWord(String fileName, HttpServletResponse response, XWPFDocument document) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".docx", "UTF-8"));
            document.write(response.getOutputStream());
            document.close();
            response.getOutputStream().close();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载Word失败");
        }
    }

    public static void downLoadPdf(String fileName, HttpServletResponse response, XWPFDocument document) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));
            PdfUtil.docToPdf(document, response.getOutputStream());
            document.close();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载Word失败");
        }
    }



}
